<template>
  <div class="config-file-view">
    <el-card shadow="never" class="main-card">
      <div class="header-bar flex items-center mb-4">
        <el-button type="primary" icon="Back" size="small" @click="goBack">返回</el-button>
        <span class="ml-4 font-bold text-lg">服务：{{ service }}</span>
        <el-button-group class="ml-8">
          <el-button
            v-for="file in fileList"
            :key="file"
            :type="fileName === file ? 'primary' : 'default'"
            size="small"
            @click="switchFile(file)"
          >
            {{ file }}
          </el-button>
        </el-button-group>
        <el-button v-if="!isEditing" type="primary" class="ml-8" @click="startEdit">编辑</el-button>
        <el-button
          v-if="isEditing"
          type="primary"
          class="ml-8"
          :loading="saving"
          @click="handleSave"
        >
          保存
        </el-button>
        <el-button v-if="isEditing" class="ml-2" @click="cancelEdit">取消</el-button>
      </div>
      <el-skeleton v-if="loading" :rows="8" animated />
      <div v-else class="code-container">
        <Codemirror
          v-model:value="fileContent"
          :options="{ ...cmOptions, readOnly: !isEditing }"
          border
          height="500px"
          width="100%"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import Codemirror from "codemirror-editor-vue3";
import "codemirror/mode/yaml/yaml.js";
import { ElMessage } from "element-plus";
import yaml from "js-yaml";
import LocalAPI from "@/api/manger/local/index";

const route = useRoute();
const router = useRouter();

const service = ref<string>((route.params.service as string) || "");
const fileName = ref<string>("");
const fileContent = ref<string>("");
const loading = ref(false);
const id = ref<string | number | undefined>((route.query.id as string) || undefined);
const configName = ref<string>((route.query.name as string) || "");
const deployType = ref<string>((route.query.deployType as string) || "");
const fileList = ref<string[]>([]); // 动态yml文件列表
const configMap = ref<Record<string, object>>({}); // 存储所有yml内容
const saving = ref(false);
const isEditing = ref(false);
const originalContent = ref("");

const cmOptions = {
  mode: "text/x-yaml",
  lineNumbers: true,
  readOnly: false, // 支持编辑
  theme: "default",
};

function mapToObj(map: any): Record<string, object> {
  if (map instanceof Map) {
    const obj: Record<string, object> = {};
    for (const [k, v] of map.entries()) {
      obj[k] = v instanceof Map ? mapToObj(v) : v;
    }
    return obj;
  }
  return map;
}

async function fetchFileList() {
  loading.value = true;
  try {
    // 调用真实接口
    const res = await LocalAPI.getConfigList(Number(id.value), service.value);
    configMap.value = mapToObj(res) || {};
    fileList.value = Object.keys(configMap.value);
    console.log("fetchFileList: fileList.value =", fileList.value);
    if (fileList.value.length > 0) {
      fileName.value = fileList.value[0];
      console.log("fetchFileList: 默认选中 fileName =", fileName.value);
      fetchConfigFile();
    }
  } catch {
    ElMessage.error("加载配置文件列表失败");
    fileList.value = [];
    configMap.value = {};
  } finally {
    loading.value = false;
  }
}

function switchFile(name: string) {
  if (fileName.value !== name) {
    fileName.value = name;
    console.log("switchFile: 切换 fileName =", fileName.value);
    fetchConfigFile();
  }
}

async function fetchConfigFile() {
  loading.value = true;
  try {
    // 取当前文件名对应的对象内容
    const obj = configMap.value[fileName.value];
    fileContent.value = obj ? yaml.dump(obj) : "";
    console.log("fetchConfigFile: fileName =", fileName.value, "fileContent =", fileContent.value);
  } catch {
    ElMessage.error("加载配置文件失败");
    fileContent.value = "";
  } finally {
    loading.value = false;
  }
}

function startEdit() {
  isEditing.value = true;
  originalContent.value = fileContent.value;
}
function cancelEdit() {
  isEditing.value = false;
  fileContent.value = originalContent.value;
}
async function handleSave() {
  saving.value = true;
  try {
    await LocalAPI.saveConfig(Number(id.value), service.value, fileName.value, fileContent.value);
    ElMessage.success("保存成功");
    isEditing.value = false;
  } catch {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
}

watch(fileName, (val) => {
  console.log("watch fileName:", val);
});
watch(fileContent, (val) => {
  console.log("watch fileContent:", val);
});

function goBack() {
  // 优先返回上一个页面，兜底跳首页，并始终带上id、name、deployType参数
  const query = {
    id: id.value,
    name: configName.value,
    deployType: deployType.value,
  };
  console.log("goBack: 返回时带的参数", query);
  if (window.history.length > 1) {
    router.back();
    setTimeout(() => {
      const current = router.currentRoute.value;
      if (!current.query.id && id.value) {
        router.replace({ path: current.path, query: { ...current.query, ...query } });
      }
    }, 300);
  } else if (id.value) {
    router.push({ path: "/", query });
  } else {
    router.push("/");
  }
}

onMounted(() => {
  // 进入页面时自动带上id
  console.log("ConfigFileView onMounted: 进入页面参数", {
    id: id.value,
    name: configName.value,
    deployType: deployType.value,
  });
  if (!route.query.id && id.value) {
    router.replace({ path: route.path, query: { ...route.query, id: id.value } });
  }
  fetchFileList();
});
</script>

<style scoped>
.config-file-view {
  padding: 24px;
}
.code-container {
  margin-top: 12px;
}
</style>
